﻿<h1>Reflections in Go</h1>

<p>
Go is a static language with well reflection support.
The remaining of this article will explain the reflection functionalities
provided in the <code>reflect</code> standard package.
</p>

<p>
It is very helpful to read the <a href="type-system-overview.html">overview
of Go type system</a> and <a href="interface.html">interfaces in Go</a> articles
before reading the remaining of the current article.
</p>

<h3>Overview of Go Reflection</h3>

<p>
From <a href="generic.html">the last article</a>,
we know that currently Go lacks of generic support for custom types and functions.
Go reflection brings many dynamic functionalities to Go programming,
which makes up for the lacking of custom generic problem to some extent
(though the reflection way is less efficient than real generic from the CPU consuming view).
Many standard code packages, such as the <code>fmt</code> and <code>encoding</code>
packages, heavily rely on the reflection functionalities heavily.
</p>

<p>
We can inspect Go values through the values of the <code>Type</code> and
<code>Value</code> types defined in the <code>reflect</code> standard package.
The following two sections will show some examples on how to use
values of the two types.
</p>

<p>
One of the Go reflection design goals is any non-reflection operation
should be also possible to be applied through the reflection ways.
For all kinds of reasons, this goal is not 100 percent achieved currently (Go 1.13).
However, most non-reflection operations can be applied through the reflection ways now.
On the other hand, through the reflection ways, we can do some operations
which are impossible to be achieved through non-reflection ways.
The operations which can't and can only be achieved through the reflection ways
will be mentioned in the following sections.
</p>

<h3>The <code>reflect.Type</code> Type and Values</h3>

<div>
<p>
In Go, we can create a <code>reflect.Type</code> value from an arbitrary
non-interface value by calling the <code>reflect.TypeOf</code> function.
The result <code>reflect.Type</code> value represents the type of the non-interface value.
Surely, we can also pass an interface value to a <code>reflect.TypeOf</code> function call,
but the call will return a <code>reflect.Type</code> value which represents the dynamic type of the interface value.
In fact, the <code>reflect.TypeOf</code> function has only one parameter of type <code>interface{}</code>
and always returns a <code>reflect.Type</code> value which represents the dynamic type of the only interface parameter.
Then how to get a <code>reflect.Type</code> value which represents an interface type?
We must use indirect ways which will be introduced below to achieve this goal.
</p>

<p>
The <code>reflect.Type</code> type is an interface type.
It <a href="https://golang.org/pkg/reflect/#Type">specifies several methods</a>.
We can call these methods to inspect the information of the type represented
by a <code>reflect.Type</code> receiver value.
Some of these methods apply for all
<a href="https://golang.org/pkg/reflect/#Kind">kinds of types</a>,
some of them are one kind or several kinds specific.
Please read the documentation of each method for details.
Calling one of the methods through an improper <code>reflect.Type</code> receiver value will produce a panic.
</p>

An example:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	type A = [16]int16
	var c <-chan map[A][]byte
	tc := reflect.TypeOf(c)
	fmt.Println(tc.Kind())    // chan
	fmt.Println(tc.ChanDir()) // <-chan
	tm := tc.Elem()
	ta, tb := tm.Key(), tm.Elem()
	// The next line prints: map array slice
	fmt.Println(tm.Kind(), ta.Kind(), tb.Kind())
	tx, ty := ta.Elem(), tb.Elem()

	// byte is an alias of uint8
	fmt.Println(tx.Kind(), ty.Kind()) // int16 uint8
	fmt.Println(tx.Bits(), ty.Bits()) // 16 8
	fmt.Println(tx.ConvertibleTo(ty)) // true
	fmt.Println(tb.ConvertibleTo(ta)) // false

	// Slice and map types are incomparable.
	fmt.Println(tb.Comparable()) // false
	fmt.Println(tm.Comparable()) // false
	fmt.Println(ta.Comparable()) // true
	fmt.Println(tc.Comparable()) // true
}
</code></pre>

<p>
There are <a href="https://golang.org/pkg/reflect/#Kind">26 kinds of types</a> in Go.
</p>

In the above example, we use the method <code>Elem</code> to get
the element types of some container types (a channel type, a map type,
a slice type and an array type).
In fact, we can also use this method to get the base type of a pointer type.
For example,

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

type T []interface{m()}
func (T) m() {}

func main() {
	tp := reflect.TypeOf(new(interface{}))
	tt := reflect.TypeOf(T{})
	fmt.Println(tp.Kind(), tt.Kind()) // ptr slice

	// Get two interface Types indirectly.
	ti, tim := tp.Elem(), tt.Elem()
	// The next line prints: interface interface
	fmt.Println(ti.Kind(), tim.Kind())

	fmt.Println(tt.Implements(tim))  // true
	fmt.Println(tp.Implements(tim))  // false
	fmt.Println(tim.Implements(tim)) // true

	// All types implement any blank interface type.
	fmt.Println(tp.Implements(ti))  // true
	fmt.Println(tt.Implements(ti))  // true
	fmt.Println(tim.Implements(ti)) // true
	fmt.Println(ti.Implements(ti))  // true
}
</code></pre>

<p>
</p>

We can get the field type and (exported) method information of a type through reflection.
We can also get the parameter and result type information of a function type
through reflection.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

type F func(string, int) bool
func (f F) Validate(s string) bool {
	return f(s, 32)
}

func main() {
	var x struct {
		n int
		f F
	}
	tx := reflect.TypeOf(x)
	fmt.Println(tx.Kind())     // struct
	fmt.Println(tx.NumField()) // 2
	tf := tx.Field(1).Type
	fmt.Println(tf.Kind())               // func
	fmt.Println(tf.IsVariadic())         // false
	fmt.Println(tf.NumIn(), tf.NumOut()) // 2 1
	fmt.Println(tf.NumMethod())          // 1
	ts, ti, tb := tf.In(0), tf.In(1), tf.Out(0)
	// The next line prints: string int bool
	fmt.Println(ts.Kind(), ti.Kind(), tb.Kind())
}
</code></pre>

<p>
Note, the <code>reflect.Type.NumMethod</code> only returns the number of exported methods of a type.
</p>

Beside the <code>reflect.TypeOf</code> function,
we can also use some other functions in the <code>reflect</code>
standard package to create <code>reflect.Type</code> values
which represent some non-defined composite types.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	ta := reflect.ArrayOf(5, reflect.TypeOf(123))
	fmt.Println(ta) // [5]int
	tc := reflect.ChanOf(reflect.SendDir, ta)
	fmt.Println(tc) // chan<- [5]int
	tp := reflect.PtrTo(ta)
	fmt.Println(tp) // *[5]int
	ts := reflect.SliceOf(tp)
	fmt.Println(ts) // []*[5]int
	tm := reflect.MapOf(ta, tc)
	fmt.Println(tm) // map[[5]int]chan<- [5]int
	tf := reflect.FuncOf([]reflect.Type{ta},
				[]reflect.Type{tp, tc}, false)
	fmt.Println(tf) // func([5]int) (*[5]int, chan<- [5]int)
	tt := reflect.StructOf([]reflect.StructField{
		{Name: "Age", Type: reflect.TypeOf("abc")},
	})
	fmt.Println(tt)            // struct { Age string }
	fmt.Println(tt.NumField()) // 1
}
</code></pre>

<p>
</p>

<p>
There are more <code>reflect.Type</code> methods which are not used
in above examples, please read the <code>reflect</code> package
documentation for their usages.
</p>

<p>
Note, up to now (Go 1.13), there are no ways to create interface types through reflection.
This is a known limitation of Go reflection.
</p>

<p>
Another limitation is, although we can create a struct type embedding other types as anonymous fields
through reflection, the struct type may or may not obtain the methods of the embedded types,
and creating a struct type with anonymous fields even might panic at run time.
In other words, the behavior of creating struct types with anonymous fields is partially compiler dependent.
</p>

<p>
The third limitation is we can't declare new types through reflection.
</p>

</div>

<h3>The <code>reflect.Value</code> Type and Values</h3>

<div>
<p>
Similarly, we can create a <code>reflect.Value</code> value from an arbitrary
non-interface value by calling the <code>reflect.ValueOf</code> function.
The result <code>reflect.Value</code> value represents the non-interface value.
Same as the <code>reflect.TypeOf</code> function, the <code>reflect.ValueOf</code> function
also has only one parameter of type <code>interface{}</code>.
When an interface argument is passed to a <code>reflect.ValueOf</code> function call,
the call will return a <code>reflect.Value</code> value which represents the dynamic value of the interface argument.
To get a <code>reflect.Value</code> value which represents an interface value,
we must use indirect ways which will be introduced below to achieve this goal.
</p>

<p>
The value represented by a <code>reflect.Value</code> value <code>v</code>
is often called the underlying value of <code>v</code>.
</p>

<p>
There are <a href="https://golang.org/pkg/reflect/">plenty of methods</a>
declared for the <code>reflect.Value</code> type.
We can call these methods to inspect the information of (and manipulate)
the underlying value of a <code>reflect.Value</code> receiver value.
Some of these methods apply for all kinds of values, some of them are one kind or several kinds specific.
Please read the <code>reflect</code> standard package documentation for details.
Calling a kind-specific method with an improper <code>reflect.Value</code> receiver value will produce a panic.
</p>

<p>
The <code>CanSet</code> method of a <code>reflect.Value</code> value
returns whether or not the underlying value of the
<code>reflect.Value</code> value is modifiable (can be assigned to).
If the Go value is modifiable, we can call the <code>Set</code> method
of the corresponding <code>reflect.Value</code> value to modify the Go value.
Note, the <code>reflect.Value</code> values returned directly by
<code>reflect.ValueOf</code> function calls are always read-only.
</p>

An example:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	n := 123
	p := &n
	vp := reflect.ValueOf(p)
	fmt.Println(vp.CanSet(), vp.CanAddr()) // false false
	vn := vp.Elem() // get the value referenced by vp
	fmt.Println(vn.CanSet(), vn.CanAddr()) // true true
	vn.Set(reflect.ValueOf(789)) // <=> vn.SetInt(789)
	fmt.Println(n)               // 789
}
</code></pre>

<p>
</p>

Non-exported fields of struct values can't be modified through reflections.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	var s struct {
		X interface{} // an exported field
		y interface{} // a non-exported field
	}
	vp := reflect.ValueOf(&s)
	// If vp represents a pointer. the following
	// line is equivalent to "vs := vp.Elem()".
	vs := reflect.Indirect(vp)
	// vx and vy both represent interface values.
	vx, vy := vs.Field(0), vs.Field(1)
	fmt.Println(vx.CanSet(), vx.CanAddr()) // true true
	// vy is addressable but not modifiable.
	fmt.Println(vy.CanSet(), vy.CanAddr()) // false true
	vb := reflect.ValueOf(123)
	vx.Set(vb)     // okay, for vx is modifiable
	// vy.Set(vb)  // will panic, for vy is unmodifiable
	fmt.Println(s) // {123 &lt;nil&gt;}
	fmt.Println(vx.IsNil(), vy.IsNil()) // false true
}
</code></pre>

<p>
</p>

From the above two examples, we can learn that there are two ways to get a <code>reflect.Value</code> value
whose underlying value is referenced by the underlying value (a pointer value) of another <code>reflect.Value</code> value.
<ol>
<li>
	One way is by calling the <code>Elem</code> method of a <code>reflect.Value</code> value
	which represents the pointer value.
</li>
<li>
	The other way is to pass a <code>reflect.Value</code> value which represents the pointer value
	to a <code>reflect.Indirect</code> function call.
	(If the argument passed to a <code>reflect.Indirect</code> function call doesn't
	represent a pointer value, then the call returns a copy of the argument.)
</li>
</ol>

Note, the <code>reflect.Value.Elem</code> method can be also used to get a <code>reflect.Value</code> value
which represents the dynamic value of an interface value. For example,

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	var z = 123
	var y = &z
	var x interface{} = y
	v := reflect.ValueOf(&x)
	vx := v.Elem()
	vy := vx.Elem()
	vz := vy.Elem()
	vz.Set(reflect.ValueOf(789))
	fmt.Println(z) // 789
}
</code></pre>

<p>
</p>

The <code>reflect</code> standard package also declares
some <code>reflect.Value</code> related functions.
Each of these functions corresponds to a built-in function
or a non-reflection functionality,
The following example demonstrates how to bind a custom generic function
to different function values.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func InvertSlice(args []reflect.Value) (result []reflect.Value) {
	inSlice, n := args[0], args[0].Len()
	outSlice := reflect.MakeSlice(inSlice.Type(), 0, n)
	for i := n-1; i >= 0; i-- {
		element := inSlice.Index(i)
		outSlice = reflect.Append(outSlice, element)
	}
	return []reflect.Value{outSlice}
}

func Bind(p interface{}, f func ([]reflect.Value) []reflect.Value) {
	// invert represents a function value.
	invert := reflect.ValueOf(p).Elem()
	invert.Set(reflect.MakeFunc(invert.Type(), f))
}

func main() {
	var invertInts func([]int) []int
	Bind(&invertInts, InvertSlice)
	fmt.Println(invertInts([]int{2, 3, 5})) // [5 3 2]

	var invertStrs func([]string) []string
	Bind(&invertStrs, InvertSlice)
	fmt.Println(invertStrs([]string{"Go", "C"})) // [C Go]
}
</code></pre>

<p>
</p>

If the underlying value of a <code>reflect.Value</code> is a function value,
then we can call the <code>Call</code> method of the <code>reflect.Value</code>
to call the underlying function.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

type T struct {
	A, b int
}

func (t T) AddSubThenScale(n int) (int, int) {
	return n * (t.A + t.b), n * (t.A - t.b)
}

func main() {
	t := T{5, 2}
	vt := reflect.ValueOf(t)
	vm := vt.MethodByName("AddSubThenScale")
	results := vm.Call([]reflect.Value{reflect.ValueOf(3)})
	fmt.Println(results[0].Int(), results[1].Int()) // 21 9

	neg := func(x int) int {
		return -x
	}
	vf := reflect.ValueOf(neg)
	fmt.Println(vf.Call(results[:1])[0].Int()) // -21
	fmt.Println(vf.Call([]reflect.Value{
		vt.FieldByName("A"), // panic on changing to "b"
	})[0].Int()) // -5
}
</code></pre>

<p>
Please note that, non-exported fields shouldn't be used as arguments of reflection calls.
If the line <code>vt.FieldByName("A")</code> in the above example is replaced
with <code>vt.FieldByName("b")</code>, a panic will occur.
</p>

A reflection example for map values.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	valueOf := reflect.ValueOf
	m := map[string]int{"Unix": 1973, "Windows": 1985}
	v := valueOf(m)
	// A zero second Value argument means to delete an entry.
	v.SetMapIndex(valueOf("Windows"), reflect.Value{})
	v.SetMapIndex(valueOf("Linux"), valueOf(1991))
	for i := v.MapRange(); i.Next(); {
		fmt.Println(i.Key(), "\t:", i.Value())
	}
}
</code></pre>

<p>
Please note that, the <code>MapRange</code> method is supported since Go 1.12.
</p>

A reflection example for channel values.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	c := make(chan string, 2)
	vc := reflect.ValueOf(c)
	vc.Send(reflect.ValueOf("C"))
	succeeded := vc.TrySend(reflect.ValueOf("Go"))
	fmt.Println(succeeded) // true
	succeeded = vc.TrySend(reflect.ValueOf("C++"))
	fmt.Println(succeeded) // false
	fmt.Println(vc.Len(), vc.Cap()) // 2 2
	vs, succeeded := vc.TryRecv()
	fmt.Println(vs.String(), succeeded) // C true
	vs, sentBeforeClosed := vc.Recv()
	fmt.Println(vs.String(), sentBeforeClosed) // Go false
	vs, succeeded = vc.TryRecv()
	fmt.Println(vs.String()) // &lt;invalid Value&gt;
	fmt.Println(succeeded)   // false
}
</code></pre>

<p>
The <code>TrySend</code> and <code>TryRecv</code> methods correspond to
one-case-one-default <a href="channel.html#select"><code>select</code>
control flow code blocks</a>.
</p>

We can use the <code>reflect.Select</code> function to simulate a
<code>select</code> code block with dynamic number of <code>case</code> branches
at run time.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "reflect"

func main() {
	c := make(chan int, 1)
	vc := reflect.ValueOf(c)
	succeeded := vc.TrySend(reflect.ValueOf(123))
	fmt.Println(succeeded, vc.Len(), vc.Cap()) // true 1 1

	vSend, vZero := reflect.ValueOf(789), reflect.Value{}
	branches := []reflect.SelectCase{
		{Dir: reflect.SelectDefault, Chan: vZero, Send: vZero},
		{Dir: reflect.SelectRecv, Chan: vc, Send: vZero},
		{Dir: reflect.SelectSend, Chan: vc, Send: vSend},
	}
	selIndex, vRecv, closed := reflect.Select(branches)
	fmt.Println(selIndex)    // 1
	fmt.Println(closed)      // true
	fmt.Println(vRecv.Int()) // 123
	vc.Close()
	// Remove the send case branch this time,
	// for it may cause panic.
	selIndex, _, closed = reflect.Select(branches[:2])
	fmt.Println(selIndex, closed) // 1 false
}
</code></pre>

<p>
</p>

The respective underlying values of some <code>reflect.Value</code> values may be nothing.
For example, zero <code>reflect.Value</code> values.

<pre class="line-numbers"><code class="language-go">package main

import "reflect"
import "fmt"

func main() {
	var z reflect.Value // a zero Value value
	fmt.Println(z)      // &lt;invalid reflect.Value&gt;
	v := reflect.ValueOf((*int)(nil)).Elem()
	fmt.Println(v)      // &lt;invalid reflect.Value&gt;
	fmt.Println(v == z) // true
	var i = reflect.ValueOf([]interface{}{nil}).Index(0)
	fmt.Println(i)             // &lt;nil&gt;
	fmt.Println(i.Elem() == z) // true
	fmt.Println(i.Elem())      // &lt;invalid reflect.Value&gt;
}
</code></pre>

<p>
</p>

For a Go value, we can use the <code>reflect.ValueOf</code> function to create a <code>reflect.Value</code> value
representing the Go value, through the help of <code>interface{}</code>.
The inverse process in similar, we can call the <code>Interface</code> method of a <code>reflect.Value</code> value
to get an <code>interface{}</code> value, then type assert on the <code>interface{}</code> value
to the Go value represented by (a.k.a., the underlying value of ) the <code>reflect.Value</code> value.

<pre class="line-numbers"><code class="language-go">package main

import "reflect"
import "fmt"

func main() {
	vx := reflect.ValueOf(123)
	vy := reflect.ValueOf("abc")
	vz := reflect.ValueOf([]bool{false, true})

	x := vx.Interface().(int)
	y := vy.Interface().(string)
	z := vz.Interface().([]bool)
	fmt.Println(x, y, z) // 123 abc [false true]
}
</code></pre>

<p>
</p>

<p>
Since Go 1.13, we can use the method <code>reflect.Value.IsZero</code> to
check whether or not the underlying value of a <code>reflect.Value</code> value is a zero value.
</p>

<a class="anchor" id="deep-equal"></a>
<p>
There are more <code>reflect.Value</code> related functions and methods
which are not used in above examples,
please read the <code>reflect</code> package documentation for their usages.
In addition, please note that there are
<a href="details.html#reflect-deep-equal">some reflection</a> related
<a href="details.html#reflect-value-bytes">details</a>
mentioned in <a href="details.html">Go details 101</a>.
</p>
</div>



<!--

bug setcion in reflect docs

interface type numbe methods, non-exported, ...


https://github.com/golang/go/issues/15924
https://github.com/golang/go/issues/16522
https://github.com/golang/go/issues/20824

https://github.com/golang/go/issues/22073

https://github.com/golang/go/issues/22075
* bug on reflect query method of interface type and value

https://github.com/golang/go/issues/22143

https://github.com/golang/go/issues/20541

https://github.com/golang/go/issues/20013



https://groups.google.com/forum/#!msg/golang-dev/coyYwxU3dfM/K_nSPAbOY4kJ;context-place=searchin/golang-dev/closure$20$20callable$20pointer%7Csort:date

reflect.StructOf: StructOf currently does not generate wrapper methods for embedded fields.
                  This limitation may be lifted in a future version.

reflect.StructOf: anonymous fields: will not produce methods table

https://github.com/golang/go/issues/15924

https://github.com/golang/go/issues/24781

https://github.com/golang/go/issues/20633
https://github.com/golang/go/issues/20632
https://github.com/golang/go/issues/20824

https://github.com/golang/go/issues/24782
* https://play.golang.org/p/Kd4igw-vOp7
* https://play.golang.org/p/KCvFWtWRC1b

https://github.com/golang/go/issues/25400 (not a bug)
https://github.com/golang/go/issues/25401
https://github.com/golang/go/issues/25402
https://github.com/golang/go/issues/25403

https://github.com/golang/go/issues/28761
https://github.com/golang/go/issues/28748

https://github.com/golang/go/issues/29381

============================================




================

reflectutil
* UnderlyingTypeOf(.)
* IsZeroValue(.)
  make using of reflect.Zero(type)

======================

generally, reflect can do any things non-reflect ways can do (not including the unsafe ways)
reflect even can do non-relfect ways can't do.
* SetLen and SetCap
* select any number of cases
* get the kind of a value
* convert []MyByte to []byte

-->
